package com.huaqing.gamerun;

import com.huaqing.games.GameStandard;
import com.huaqing.games.impl.GameStandardImpl;
import com.huaqing.memory.SingletonMemory;
import com.huaqing.users.Machine;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;


/**
 * @program: javatrainingfirstweek
 * @Description:
 * @author: Mr.Cheng
 * @date: 2022/4/11 7:22 下午
 */
@Slf4j
public class RockPaperScissorsThread implements Runnable{
    private Machine person;
    private Machine machine;
    private CountDownLatch latch;

    public RockPaperScissorsThread(Machine person, Machine machine) {
        this.person = person;
        this.machine = machine;
    }

    public RockPaperScissorsThread(Machine person, Machine machine, CountDownLatch latch) {
        this.person = person;
        this.machine = machine;
        this.latch = latch;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        GameStandard standard = new GameStandardImpl();
        SingletonMemory memory = SingletonMemory.getSingleton();
        try {
            for (int i = 0; i < person.getOperations().length; i++) {
                int personResult = person.getOperations()[i];
                int computerResult = machine.getOperations()[i];
                memory.getResultList().add(standard.rockPaperScissors(personResult, computerResult));
            }
        }catch (Throwable e){
            log.error("can not play",e);
        }finally {
            //很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
            //递减锁存器的计数，如果计数到达零，则释放所有等待的线程。
            latch.countDown();
            //如果当前计数大于零，则将计数减少 1
        }
    }
}
